﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using UploadFile.Common;
using UploadFile.Models;

namespace UploadFile.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DownloadFileController : ControllerBase
    {

        private readonly ICrudProvider _crudProvider;

        public DownloadFileController(ICrudProvider crudProvider)
        {
            this._crudProvider = crudProvider;
        }

        // GET: api/DownloadFile
        [HttpGet]
        public string Get()
        {
            return "DownloadFile Get";
        }

        // GET: api/DownloadFile/5
        [HttpGet("{fileId}")]
        public async Task<ActionResult> Download(string fileId)
        {
            Guid fileGuid = Guid.Empty;
            try
            {
                fileGuid = new Guid(fileId);
            }
            catch (Exception ex)
            {
                return NotFound("未找到下载文件");
            }
            FileData fileData = await _crudProvider.GetByIdAsync<FileData>(fileGuid);
            if(fileData == null)
                return NotFound("未找到下载文件");
            string filePath = fileData.FilePath;
            string fileExt = Path.GetExtension(fileData.FilePath);
            fileExt = fileExt.Substring(1, fileExt.Length - 1);
            string fileDownloadName = fileData.FileName;
            return PhysicalFile(filePath, "application/octet-stream", fileDownloadName);
        }
    }
}
